/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
$(function() {
    var user_id = parseInt(getURLParameter("user"));
    var run_id = parseInt(getURLParameter("run"));
    this.pulseAvg = 0;
    this.altAvg = 0;
    this.speedAvg = 0;
    me=this;
    
    getButtons(user_id);
    
    $("#icons li").hover(
            function() {
                $(this).addClass("ui-state-hover");
            },
            function() {
                $(this).removeClass("ui-state-hover");
            });
            
    $("#icons li").on("click", function() {
        var def_runrem = removeRun(user_id, run_id);
        def_runrem.done(function() {
            //alert("Success");
            window.location.href = '/webappz-gu/user.jsp?user=' + user_id;
        });
        def_runrem.fail(function(evt) {
            //alert("Failed: " + evt.toString());
            window.location.href = '/webappz-gu/user.jsp?user=' + user_id;
        });
    });

    /*
    * Get a deferred object for run
    */
    var def_run = getSingleRun(user_id, run_id);

    /*
    * When deferred run is done, do...
    */
    def_run.done(function(run) {
        console.log(run);
        trackName = run.trackName;
        date = new Date(run.runDate).toUTCString();
        totalTime = run.totalTime;
        distance = run.distance;
        calories = run.totalCalories;
        
        // Set variables that will be used later in another scope
        me.pulseAvg = run.avgHeartRate;
        //me.altAvg = run.avgAlt;
        me.speedAvg = run.avgSpeed;

        // Append trackname, date and statistics to header
        $("#track").append("Track name: " + trackName);
        $("#date").append(date);
        $("#headstats").append("Time: " + (totalTime / 60).toFixed(2) + " minutes");
        $("#headstats").append(" | Distance: " + (distance / 1000).toFixed(2) + " km");
        $("#headstats").append(" | Calories burnt: " + (calories).toFixed(2) + " kcal");
        
    });

    /*
     * Get new frames object
     */
    var def_frames = new Frames(user_id, run_id);
    
    /*
     * Initialize a deferred frames object, when it's done do...
     */
    def_frames.initialize().done(function() {
        var frames = def_frames.getFrames();
        var pulse = def_frames.getPulses();
        var altitude = def_frames.getAltitudes();
        var speed = def_frames.getSpeeds();
        var coords = def_frames.getCoords();
        var ticks = def_frames.getTicks();

        plot_options.axes.xaxis.ticks = ticks;
        plot_options.axes.xaxis.min = pulse[0][0];
        plot_options.axes.xaxis.max = pulse[pulse.length - 1][0];
        
        plot_options.axes.x2axis = {
            show: true,
            tickOptions: {
                show: false
            },
            min: 0,
            max: frames.length
        };
        
        plot_options.title = "Heart Rate (Average " + me.pulseAvg + " bpm)";
        plot_options.axes.yaxis.max = 200;
        $.jqplot('pulse_plot', [pulse], plot_options);

        plot_options.title = "Speed (Average " + mpsToKmph(me.speedAvg).toFixed(1) + " km/h)";
        plot_options.axes.yaxis.max = 10;
        $.jqplot('speed_plot', [speed], plot_options);

        plot_options.title = "Altitude";// (Average " + me.altAvg + ")";
        plot_options.axes.yaxis.max = 100;
        $.jqplot('altitude_plot', [altitude], plot_options);
        
        /*
         * Helper for mapping mousemovement in diagrams to map position
         */
        plotMouseMove = function(ev, seriesIndex, pointIndex, data) {
            frame = Math.round(pointIndex.x2axis);
            cmap.setFramePos(frames[frame].lat, frames[frame].lon);
        };

        // Bind mouse movement to plots
        $('#pulse_plot').bind('jqplotMouseMove', plotMouseMove);
        $('#speed_plot').bind('jqplotMouseMove', plotMouseMove);
        $('#altitude_plot').bind('jqplotMouseMove', plotMouseMove);

        /*
         * Create map and set various values
         */
        var cmap = new CormacMap("map", coords);
        cmap.setMaxAltitude(def_frames.getMaxAltitude().coord, def_frames.getMaxAltitude().alt);
        cmap.setMaxSpeed(def_frames.getMaxSpeed().coord, def_frames.getMaxSpeed().speed);
        cmap.setMaxPulse(def_frames.getMaxPulse().coord, def_frames.getMaxPulse().pulse);

    });
});
